<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2023/4/19
 * Time: 16:40
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);


namespace App\Kernel\Wechat;

use EasyWeChat\MiniApp\Application;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\ContainerInterface;
use Hyperf\Guzzle\ClientFactory;

class WechatFactory
{
    /**
     * @var ContainerInterface
     */
    protected ContainerInterface $container;
    /**
     * @var Application
     */
    protected Application $wechat_app;
    /**
     * @var array
     */
    private array $config;
    private ClientFactory $clientFactory;

    /**
     * @param ContainerInterface $container
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function __construct(ContainerInterface $container,ClientFactory $clientFactory)
    {
        $this->container = $container;
        $this->config = $container->get(ConfigInterface::class)->get('wechat.mini_program.default');
        $this->wechat_app = new Application($this->config);
        $this->clientFactory =$clientFactory;
    }

    /**
     * code2session
     * @param string $code
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function session(string $code)
    {
        $data = [
            'js_code' => $code,
            'grant_type' => 'authorization_code',
            'appid'=>$this->config['app_id'],
            'secret'=>$this->config['secret']
        ];
        try {
            $server = $this->wechat_app->getUtils()->codeToSession($code);

        }catch (\Exception $e){
            var_dump($e->getMessage());
        }
        return $server;
    }

    /**
     * @param string $name
     * @param array $arguments
     * @return mixed
     */
    public function __call(string $name, array $arguments)
    {
        return call_user_func_array(array($this->wechat_app, $name), $arguments);
    }
}